#pragma once

#include <string>
#include <unistd.h>
#include <cstring>
#include "log.hpp"
#include "constants.hpp"

extern Log lg;
extern const int BUFFER_SIZE;

class fdhelper
{
public:
    fdhelper(int fd)
        :_fd(fd)
    { }

    ~fdhelper()
    {
        close(_fd);
    }

private:
    int _fd;
};

void task(int fd)
{
    //接收信息
    fdhelper fh(fd);
    char buffer[BUFFER_SIZE]; buffer[0] = 0;
    ssize_t n = read(fd, buffer, sizeof(buffer));
    if(n < 0) {
        lg(WARNING, "read err, errno:%d, errmsg:%s", errno, strerror(errno));
        return;
    }
    else if(n == 0) {
        lg(LOG, "client exit...");
        return;
    }
    lg(LOG, "read success, errno:%d, errmsg:%s", errno, strerror(errno));
    buffer[n] = 0;
    
    //回返信息
    std::string msg = "server echo# ";
    msg += buffer;
    lg(LOG, "%s", msg.c_str());
    n = write(fd, msg.c_str(), msg.size());
    if(n < 0) {
        lg(WARNING, "write err, errno:%d, errmsg:%s", errno, strerror(errno));
        return;
    }
    lg(LOG, "write success, errno:%d, errmsg:%s", errno, strerror(errno));
    //关闭连接
    close(fd);
    lg(LOG, "close client fd done");
}